{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TensorFlow BYOM: Train locally and deploy on SageMaker.\n",
    "\n",
    "\n",
    "1. [Introduction](#Introduction)\n",
    "2. [Prerequisites and Preprocessing](#Prequisites-and-Preprocessing)\n",
    "    1. [Permissions and environment variables](#Permissions-and-environment-variables)\n",
    "    2. [Model definitions](#Model-definitions)\n",
    "    3. [Data Setup](#Data-setup)\n",
    "3. [Training the network locally](#Training)\n",
    "4. [Set up hosting for the model](#Set-up-hosting-for-the-model)\n",
    "    1. [Export from TensorFlow](#Export-the-model-from-tensorflow)\n",
    "    2. [Import model into SageMaker](#Import-model-into-SageMaker)\n",
    "    3. [Create endpoint](#Create-endpoint) \n",
    "5. [Validate the endpoint for use](#Validate-the-endpoint-for-use)\n",
    "\n",
    "__Note__: Compare this with the [tensorflow bring your own model example](../tensorflow_iris_byom/tensorflow_BYOM_iris.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction \n",
    "\n",
    "This notebook can be compared to [Iris classification example notebook](../tensorflow_iris_dnn_classifier_using_estimators/tensorflow_iris_dnn_classifier_using_estimators.ipynb) in terms of its functionality. We will do the same classification task, but we will train the same network locally in the box from where this notebook is being run. We then setup a real-time hosted endpoint in SageMaker.\n",
    "\n",
    "Consider the following model definition for IRIS classification. This mode uses the ``tensorflow.estimator.DNNClassifier`` which is a pre-defined estimator module for its model definition. The model definition is the same as the one used in the [Iris classification example notebook](../tensorflow_iris_dnn_classifier_using_estimators/tensorflow_iris_dnn_classifier_using_estimators.ipynb)\n",
    "\n",
    "## Prequisites and Preprocessing\n",
    "### Permissions and environment variables\n",
    "\n",
    "Here we set up the linkage and authentication to AWS services. In this notebook we only need the roles used to give learning and hosting access to your data. The Sagemaker SDK will use S3 defualt buckets when needed. If the ``get_execution_role``  does not return a role with the appropriate permissions, you'll need to specify an IAM role arn that does."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "isConfigCell": true
   },
   "outputs": [],
   "source": [
    "import boto3, re\n",
    "from sagemaker import get_execution_role\n",
    "\n",
    "role = get_execution_role()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model Definitions\n",
    "\n",
    "We use the [``tensorflow.estimator.DNNClassifier``](https://www.tensorflow.org/api_docs/python/tf/estimator/DNNClassifier) estimator to set up our network. We also need to write some methods for serving inputs during hosting and training. These methods are all found below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat iris_dnn_classifier.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create an estimator object with this model definition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from iris_dnn_classifier import estimator_fn\n",
    "classifier = estimator_fn(run_config = None, params = None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data setup\n",
    "\n",
    "Next, we need to pull the data from tensorflow repository and make them ready for training. The following will code block should do that."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os \n",
    "from six.moves.urllib.request import urlopen\n",
    "\n",
    "# Data sets\n",
    "IRIS_TRAINING = \"iris_training.csv\"\n",
    "IRIS_TRAINING_URL = \"http://download.tensorflow.org/data/iris_training.csv\"\n",
    "\n",
    "IRIS_TEST = \"iris_test.csv\"\n",
    "IRIS_TEST_URL = \"http://download.tensorflow.org/data/iris_test.csv\"\n",
    "\n",
    "if not os.path.exists(IRIS_TRAINING):\n",
    "    raw = urlopen(IRIS_TRAINING_URL).read()\n",
    "    with open(IRIS_TRAINING, \"wb\") as f:\n",
    "      f.write(raw)\n",
    "\n",
    "if not os.path.exists(IRIS_TEST):\n",
    "    raw = urlopen(IRIS_TEST_URL).read()\n",
    "    with open(IRIS_TEST, \"wb\") as f:\n",
    "      f.write(raw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create the data input streamer object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from iris_dnn_classifier import train_input_fn\n",
    "train_func = train_input_fn('.', params = None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training\n",
    "\n",
    "It is time to train the network. Since we are training the network locally, we can make use of TensorFlow's ``tensorflow.Estimator.train`` method. The model is trained locally in the box."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "classifier.train(input_fn = train_func, steps = 1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set up hosting for the model\n",
    "\n",
    "### Export the model from tensorflow\n",
    "\n",
    "In order to set up hosting, we have to import the model from training to hosting. We will begin by exporting the model from TensorFlow and saving it down. Analogous to the [MXNet example](../mxnet_mnist_byom/mxnet_mnist.ipynb), some structure needs to be followed. The exported model has to be converted into a form that is readable by ``sagemaker.tensorflow.model.TensorFlowModel``. The following code describes exporting the model in a form that does the same:\n",
    "\n",
    "There is a small difference between a SageMaker model and a TensorFlow model. The conversion is easy and fairly trivial. Simply move the tensorflow exported model into a directory ``export\\Servo\\`` and tar the entire directory. SageMaker will recognize this as a loadable TensorFlow model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from iris_dnn_classifier import serving_input_fn\n",
    "\n",
    "exported_model = classifier.export_savedmodel(export_dir_base = 'export/Servo/', \n",
    "                               serving_input_receiver_fn = serving_input_fn)\n",
    "\n",
    "print (exported_model)\n",
    "import tarfile\n",
    "with tarfile.open('model.tar.gz', mode='w:gz') as archive:\n",
    "    archive.add('export', recursive=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import model into SageMaker\n",
    "\n",
    "Open a new sagemaker session and upload the model on to the default S3 bucket. We can use the ``sagemaker.Session.upload_data`` method to do this. We need the location of where we exported the model from TensorFlow and where in our default bucket we want to store the model(``/model``). The default S3 bucket can be found using the ``sagemaker.Session.default_bucket`` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import sagemaker\n",
    "\n",
    "sagemaker_session = sagemaker.Session()\n",
    "inputs = sagemaker_session.upload_data(path='model.tar.gz', key_prefix='model')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use the ``sagemaker.tensorflow.model.TensorFlowModel`` to import the model into SageMaker that can be deployed. We need the location of the S3 bucket where we have the model, the role for authentication and the entry_point where the model defintion is stored (``iris_dnn_classifier.py``). The import call is the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sagemaker.tensorflow.model import TensorFlowModel\n",
    "sagemaker_model = TensorFlowModel(model_data = 's3://' + sagemaker_session.default_bucket() + '/model/model.tar.gz',\n",
    "                                  role = role,\n",
    "                                  framework_version = '1.12',\n",
    "                                  entry_point = 'iris_dnn_classifier.py')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create endpoint\n",
    "\n",
    "Now the model is ready to be deployed at a SageMaker endpoint. We can use the ``sagemaker.tensorflow.model.TensorFlowModel.deploy`` method to do this. Unless you have created or prefer other instances, we recommend using 1 ``'ml.m4.xlarge'`` instance for this example. These are supplied as arguments. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "predictor = sagemaker_model.deploy(initial_instance_count=1,\n",
    "                                          instance_type='ml.m4.xlarge')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Validate the endpoint for use\n",
    "\n",
    "We can now use this endpoint to classify. Run an example prediction on a sample to ensure that it works."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sample = [6.4,3.2,4.5,1.5]\n",
    "predictor.predict(sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Delete all temporary directories so that we are not affecting the next run. Also, optionally delete the end points."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "os.remove('model.tar.gz')\n",
    "import shutil\n",
    "shutil.rmtree('export')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you do not want to continue using the endpoint, you can remove it. Remember, open endpoints are charged. If this is a simple test or practice, it is recommended to delete them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sagemaker.Session().delete_endpoint(predictor.endpoint)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_tensorflow_p27",
   "language": "python",
   "name": "conda_tensorflow_p27"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  },
  "notice": "Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
